<template>
  <UploadExcel
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
  />
</template>
<script>
import UploadExcel from '@/components/UploadExcel'
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index.js'
export default {
  name: 'Import',
  components: {
    UploadExcel
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ header, results }) {
      console.log('数据是', header, results)
      this.tableData = results
      this.tableHeader = header
      // 1. 转换格式
      //  const 后端要的格式 = this.format(results, header)
      const data = this.format(results)
      console.log('后端要的格式', data)
      // 2.发送ajax请求
      const res = await importEmployee(data)
      console.log('上传的是', res)
    },
    format(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      console.log(results)
      // 映射
      return results.map(obj => {
        const newObj = {}
        //   obj属性名是中文
        const zhKeys = Object.keys(obj) // ['姓名', '手机号']

        zhKeys.forEach(zhKey => {
          const enkey = mapInfo[zhKey]

          newObj[enkey] = obj[zhKey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            // 后端需要的日期格式是标准时间
            newObj[enkey] = new Date(formatExcelDate(obj[zhKey]))
          } else {
            newObj[enkey] = obj[zhKey]
          }
        })
        return newObj
      })
    }
  }
}
</script>
